<?php
declare(strict_types = 1);

namespace leruge;

use app\model\AuthGroup;
use app\model\AuthGroupAccess;
use app\model\AuthRule;

class Auth
{
    protected array $config = [
        'auth_on' => true, // 认证开关
        'super_id_array' => [1], // 超级管理员ID
    ];

    public function __construct()
    {
        $this->config = array_merge($this->config, config('auth'));
    }

    /**
     * @title 获取用户的权限列表
     *
     * @param integer $adminId 管理员ID
     *
     * @return array 权限数组
     */
    public function getAuthList(int $adminId) : array
    {
        $where = [];
        if ($this->config['auth_on'] && !in_array($adminId, $this->config['super_id_array'])) {
            $groupId = AuthGroupAccess::where('admin_id', $adminId)->value('group_id');
            $ruleIds = AuthGroup::where('id', $groupId)->value('rules');
            $ruleIdArray = array_filter(array_unique(explode(',', $ruleIds ?: '')));
            sort($ruleIdArray);
            $where[] = ['id', 'in', $ruleIdArray];
        }
        $ruleArray = AuthRule::where($where)->column('rule');
        $ruleArray = array_filter(array_unique($ruleArray));
        sort($ruleArray);
        return $ruleArray;
    }

    /**
     * @title 检查管理员是否有权限
     *
     * @param string|null $rule 权限规则
     * @param int $adminId 管理员ID
     *
     * @return bool 是否有权限
     */
    public function check(string $rule, int $adminId) : bool
    {
        if ($this->config['auth_on'] && !in_array($adminId, $this->config['super_id_array'])) {
            $ruleArray = $this->getAuthList($adminId);
            return in_array($rule, $ruleArray);
        } else {
            return true;
        }
    }
}